<?php

namespace app\admin\model;

use think\Model;
use think\facade\Session;
use think\facade\Request;

class AdminModel extends Model
{

    protected $table = '__ADMIN__';

    /**
     * 用户登录
     * @param $username
     * @param $password
     * @param $online
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkUser($username, $password, $online)
    {
        $user = $this->where(['username' => $username])->find();

        //是否限制用户登录(密码错误过多)
        $login_error = new AdminLoginErrorModel();
        $ban_login = $login_error->checkLoginError($username);
        if ($ban_login['status'] == 'n') {
            return $ban_login;
        }

        if (!empty($user) && $user['status'] == 1) {//用户存在，并且允许登录

            //禁止角色登陆
            $role_status = (new AdminRoleModel())->getRole($user['role_id']);
            if (empty($role_status['status'])) {
                $login_error->loginError();//用户名密码错误，记录次数
                return ['status' => 'n', 'info' => '用户名或密码错误'];
            }

            $password_md5 = md5('xsy' . md5($password) . $user['verify']);
            if ($password_md5 == $user['password']) {
                if (!empty($online)) {
                    //记住登录状态，关闭session 重开
                    session_write_close();
                    Session::init([
                        'expire' => 3600 * 24 * 30
                    ]);
                }
                //记录登录状态
                Session::set('username', $username);
                Session::set('role_id', $user['role_id']);
                //登录时间，登录ip
                $this->save(['last_login_time' => time(), 'last_login_ip' => Request::ip()], ['username' => $username]);
                return ['status' => 'y', 'info' => '登录成功'];
            } else {
                $login_error->loginError();//用户名密码错误，记录次数
                return ['status' => 'n', 'info' => '用户名或密码错误'];
            }
        } else {
            $login_error->loginError();//用户名密码错误，记录次数
            return ['status' => 'n', 'info' => '用户名或密码错误'];
        }
    }

    /**
     * 获取所有管理用户
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllUser($username)
    {
        $where = ['username' => $username];
        if (empty($username)) {
            $where = '';
        }
        return $all_user = $this->order('id asc')->where($where)->paginate();
    }

    /**
     * 根据id获取用户
     */
    public function getUser($id)
    {
        $user = $this->find($id);
        if (!empty($user)) {
            return $user->toArray();
        } else {
            return [];
        }
    }

    /**
     * 根据username获取用户
     */
    public function getUserByName($username)
    {
        $user = $this->where('username', $username)->find();
        if (!empty($user)) {
            return $user->toArray();
        } else {
            return [];
        }
    }

    public function adminAdd($post_data)
    {
        //判断用户是否被添加过
        $user = $this->where(['username' => $post_data['username']])->find();

        //用户随机数
        $post_data['verify'] = random_str(6);
        //密码加密
        $password_md5 = md5('xsy' . md5($post_data['password']) . $post_data['verify']);
        $post_data['password'] = $password_md5;
        //默认启用状态
        $post_data['status'] = 1;
        if (!empty($user)) {
            return ['status' => 'n', 'info' => '用户名已经存在'];
        }
        if ($this->allowField(true)->save($post_data)) {
            return ['status' => 'y', 'info' => '用户添加成功'];
        } else {
            return ['status' => 'n', 'info' => '用户名添加失败'];
        }
    }

    public function adminEdit($post_data)
    {
        //超级用户不允许被修改
        if ($post_data['id'] == 1) {
            return ['status' => 'n', 'info' => '超级管理员不允许此操作'];
        }
        //判断用户是否被添加过
        $user = $this->where(['username' => $post_data['username']])->find();
        if (!empty($user) && $user['id'] != $post_data['id']) {
            return ['status' => 'n', 'info' => '用户名已经存在'];
        }

        //是否修改密码
        if (!empty($post_data['password'])) {
            //密码加密
            $password_md5 = md5('xsy' . md5($post_data['password']) . $user['verify']);
            $post_data['password'] = $password_md5;
        } else {
            unset($post_data['password']);
        }

        if ($this->allowField(true)->save($post_data, ['id' => $post_data['id']])) {
            return ['status' => 'y', 'info' => '用户修改成功'];
        } else {
            return ['status' => 'n', 'info' => '用户名修改失败'];
        }
    }

    public function myInfo($post_data)
    {
        $user = $this->find($post_data['id']);
        if ($user['username'] != Session::get('username')) {
            return ['status' => 'n', 'info' => '只能修改自己的数据'];
        }

        //是否修改密码
        if (!empty($post_data['password'])) {
            //密码加密
            $password_md5 = md5('xsy' . md5($post_data['password']) . $user['verify']);
            $post_data['password'] = $password_md5;
        } else {
            unset($post_data['password']);
        }

        if ($this->allowField(true)->save($post_data, ['id' => $post_data['id']])) {
            return ['status' => 'y', 'info' => '用户修改成功', 'edit_pwd' => !empty($post_data['password']) ? 1 : 0];
        } else {
            return ['status' => 'n', 'info' => '用户名修改失败'];
        }
    }

}